package com.yanghui.dtracing.plugin.feign;

import com.yanghui.dtracing.core.opentracing.DTracerSpan;
import com.yanghui.dtracing.core.opentracing.Tracing;
import com.yanghui.dtracing.core.plugin.interceptor.IInstanceMethodAroundInterceptor;
import com.yanghui.dtracing.core.plugin.interceptor.MethodInterceptResult;
import io.opentracing.Span;
import io.opentracing.tag.Tags;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URI;

public class FeignLoadBalancerInstanceMethodInterceptor implements IInstanceMethodAroundInterceptor {


    @Override
    public void beforeMethod(Object thisObj, Method method, Object[] allArguments, MethodInterceptResult result) throws Throwable {
        Span span = Tracing.getTracer().activeSpan();
        if(null == span){
            return;
        }
        DTracerSpan tracerSpan = (DTracerSpan)span;
        if(!"feign.SynchronousMethodHandler".equals(tracerSpan.getClassName())){
            return;
        }
        URI uri = getUri(allArguments[0]);
        tracerSpan.setTag(Tags.PEER_PORT,uri.getPort())
                .setTag(Tags.PEER_HOSTNAME,uri.getHost());
    }

    private URI getUri(Object ribbonRequest) throws Exception{
        Field field = ribbonRequest.getClass().getSuperclass().getDeclaredField("uri");
        field.setAccessible(true);
        return (URI)field.get(ribbonRequest);
    }
}
